<template>
	<div class="contentDiv">
		<x-header>安检信息</x-header>
		<a href="javascript:;" class="save" @click="saveAction(function(){})">保存</a>
		<a href="javascript:;" class="submit" @click="submitAction">提交</a>
		<div class="userInfo">
			<div class="topDiv">
				<img src="../../assets/img/securityCheckImg/head.png" />
				<div class="nameAddress">
					<p class="name">{{CUST_ADDRINFO.CONS_NAME}}({{CUST_ADDRINFO.CONS_NO}})</p>
					<p class="address">用户地址：{{CUST_ADDRINFO.CONS_ADDR}}</p>
					<div class="trouble">
						<p class="p1">{{CUST_ADDRINFO.CONS_SORT_NAME}}/{{CUST_ADDRINFO.CONS_STAT_NAME}} {{CUST_ADDRINFO.RESIDENT_POPU == ''?'0':CUST_ADDRINFO.RESIDENT_POPU}}人</p>
						<p class="p2"><span id="title">隐患:</span><span id="number">{{troubleList.length}}个</span></p>
					</div>
				</div>
			</div>
			<div class="line"></div>
			<div class="bottomDiv">
				<input type="text" placeholder="请输入现名称" v-model=presentName />
				<div style="background-color:#D9DAEB;width:1px;height: 0.4166rem;"></div>
				<div class="lableDiv">
					<tag></tag>
					<!--<p><span style="font-size: 0.3888rem;color: #444444;margin-right: 0.6944rem;">标签</span><span style="font-size: 0.3333rem;color: #FE6261;">宠 </span><span style="font-size: 0.3333rem;color: #FFA600;">暖 </span><span style="font-size: 0.3333rem;color: #159BFD;">外 </span></p>
					<img src="../../assets/img/securityCheckImg/rightArrow.png" />-->
				</div>
			</div>

		</div>
		<div class="workOrderInfo">
			<div class="order">
				<div>
					<div style="background-color:#159BFD;width:0.0833rem;height:0.3888rem;margin-left: 0.2777rem;margin-top: 0.3472rem;"></div>
					<p style="margin-top: 0.3472rem;margin-left: 0.2777rem;color: #444444;font-size: 0.4166rem;margin-bottom: 0.3472rem;">工单信息</p>
				</div>
				<div @click="orderShowAction($event.currentTarget)">
					<p style="font-size:0.3611rem;color: #888;margin-top: 0.3611rem;">{{CUST_ADDRINFO.APP_NO}}</p>
					<img v-if="this.orderShow" src="../../assets/img/securityCheckImg/upArrow.png" class="topImg" />
					<img v-else src="../../assets/img/securityCheckImg/rightArrow.png" class="rightImg" />
				</div>
			</div>
			<div v-show="orderShow">
				<div style="display: flex;">
					<img src="../../assets/img/securityCheckImg/reservation.png" style="width: 0.4444rem;height: 0.4444rem;margin-left: 0.2777rem;margin-top: 0.2083rem;" />
					<p style="margin-left: 0.2777rem;margin-top: 0.2083rem;font-size: 0.4166rem;color: #444444;">预约{{tsTypeName}}</p>
				</div>
				<p style="margin-left: 0.2777rem;margin-top: 0.1388rem;padding-bottom: 0.2777rem;color: #888888;font-size: 0.3611rem;">{{remark}}</p>
			</div>
			<cell :title="title1" :value="value1"></cell>

			<!--<datetime v-model="value2" :format="format" @on-change="change" :title="预约时间"></datetime>-->

			<!--<cell :title="title2" :value="value2" :isDate="isDate"></cell>-->
			<div class="operationDiv">
				<label>作业状态</label>
				<a v-for="(operation,index) in OperationStates" @click="select($event.currentTarget,operation,index)" :key="index">
					<img v-if="operation.isChoose" src="../../assets/img/securityCheckImg/selected.png" />
					<img v-else src="../../assets/img/securityCheckImg/unselected.png" />
					<label>{{operation.CODE_NAME}}</label>
				</a>
			</div>
		</div>
		<div v-show="showEntryInfo" class="entryInfo">
			<entry :entrys="entrys" :consNo = "CONS_NO"></entry>

		</div>
		<div class="record">
			<div @click="recordAction">
				<img src="../../assets/img/securityCheckImg/record.png" />
				<p>长按录音</p>
			</div>

		</div>
	</div>
</template>

<script>
	import { XHeader, Datetime, dateFormat } from 'vux';
	import cell from "@/components/securityCheck/commonCell";
	import entry from "@/components/transact/transactInfo/entry"
	import tag from "@/components/transact/transactInfo/tag"
	import { uploadSecurityResult } from "@/utils/serviceUtils"
	import { UserInfo } from "@/utils/public"
	import { getYYYYMMddDate } from "@/utils/getsn"
	import { FEEDBACK } from "@/utils/feedback"
	import { getScRstDtl } from "@/utils/securityProjectService"
  import { commonEntrys, tsTypeNames } from "@/utils/transactService"
  import Vue from "vue";
	export default {
		data() {
			return {
				presentName: "", //现名称
				isDate: true,
				title1: "联系人",
				value1: "",
				title2: "预约时间",
				value2: "2018-05-23 11:30",
				orderShow: true,
				OperationStates: [],
				entrys: commonEntrys["0000"],
				CUST_ADDRINFO: {}, //用户基本信息
				CUST_CONTACTINFO: {}, //联系信息
				CONS_LABLEINFO: {},
				CONS_STAT: "", //用户状态 
				RESIDENT_POPU: "", //常住人口
				troubleList:[],
				showEntryInfo:true,
				remark: "",
				tsTypeName: tsTypeNames["0000"],
        CONS_NO:"",
			}
		},
		filters: {
			dateFormat
		},
		components: {
			entry,
			cell,
			XHeader,
			tag,
			Datetime

		},
		mounted() {
			this.getData();
		},
		watch: {
			isRequested(val) {
				console.log(val)
			}
		},
		methods: {
			getData() {
				var cons_no = this.$route.query.CONS_NO;
        var app_no = "";
        Vue.set(this,'CONS_NO',this.$route.query.CONS_NO)
				const _this = this;
				//获取作业状态
				AndroidApi.queryTableData('{"whereClause":"select * from p_code where code_type=? ","whereArgs":["bpHomeSitu"]}', function(msg) {
					console.log("作业状态");
					console.log(JSON.stringify(msg.result));
					if(msg.resultCode == "9999") {
						_this.OperationStates = msg.result;
						for(var i = 0; i < _this.OperationStates.length; i++) {
							_this.$set(_this.OperationStates[i], 'isChoose', false);
						}
					}
					AndroidApi.queryTableData('{"whereClause":"select * from TURC_INFO_Table where APP_NO = ?  ","whereArgs":[' + app_no + ']}', function(msg) {
						console.log(JSON.stringify(msg.result.HOME_SITU));
						if(msg.resultCode == "9999") {
							if(msg.result.length>0){
								var HOME_SITU = msg.result[0].HOME_SITU;
								_this.REMARK = msg.result[0].REMARK;
								console.log(JSON.stringify(HOME_SITU)+"HOME_SITU");
								if(HOME_SITU) {
									for(var i = 0; i < _this.OperationStates.length; i++) {
										if(_this.OperationStates[i].CODE_VALUE == HOME_SITU) {
											_this.$set(_this.OperationStates[i], 'isChoose', true);
											if(_this.OperationStates[i].CODE_VALUE == '01'){
												_this.showEntryInfo = true;
											}else{
												_this.showEntryInfo = false;
											}
											
										}
									}
								}
							}
						}
					});
				});
				//获取用户的名字和电话
				AndroidApi.queryTableData('{"whereClause":"select * from CUST_CONTACTINFO D,CONT_CHANL E where D.CONTACT_ID=E.CONTACT_ID and D.CONS_NO = ? and E.PRIORITY=1 limit 1","whereArgs":[' + cons_no + ']}', function(msg) {
					console.log("获取用户的名字和电话");
					if(msg.resultCode == "9999") {
						if(msg.result.length > 0){
							var CONTACTINFO = msg.result[0];
							_this.value1 = CONTACTINFO.CONTACT_NAME + " " + CONTACTINFO.CONT_CHANL_NO;
						}

					}
				});
				//获取用户地址信息（CUST_ADDRINFO）
				AndroidApi.queryTableData('{"jToken":"","whereClause":"select A.*,(select B.CODE_NAME from p_code B where B.code_type=\'bpConsStat\'  AND B.CODE_VALUE = A.CONS_STAT) CONS_STAT_NAME,(select B.CODE_NAME from p_code B where B.code_type=\'bpConsSortCode\' AND B.CODE_VALUE = A.CONS_SORT_CODE) CONS_SORT_NAME from CUST_ADDRINFO A where A.CONS_NO = ?","whereArgs":[' + cons_no + ']}', function(msg) {
					console.log("获取用户地址信息:" + JSON.stringify(msg));
					if(msg.resultCode == "9999") {
            console.log()
						_this.CUST_ADDRINFO = msg.result[0]||{};
						localStorage.setItem("CONS_NAME", _this.CUST_ADDRINFO.CONS_NAME);
						_this.presentName = _this.CUST_ADDRINFO.PRESENT_NAME;
					}
				});
				//获取用户联系信息（CUST_CONTACTINFO）
				AndroidApi.queryTableData('{"jToken":"","whereClause":"select * from CUST_CONTACTINFO","whereArgs":[]}', function(msg) {
					console.log("获取用户联系信息:" + JSON.stringify(msg));
					if(msg.resultCode == "9999") {
						_this.CUST_CONTACTINFO = msg.result[0];
					}
				});
				//用户标签信息（CONS_LABLEINFO）       
				AndroidApi.queryTableData('{"jToken":"","whereClause":"select * from CONS_LABLEINFO","whereArgs":[]}', function(msg) {
					console.log("获取用户标签信息:" + JSON.stringify(msg));
					if(msg.resultCode == 9999) {

					}
				});
				//获取隐患个数
				getScRstDtl(function(msg) {
					console.log("getScRstDtl");
					console.log(msg)
					_this.troubleList = [];
					if(msg) {
						console.log(msg)
						msg.forEach((element, index) => {
							_this.troubleList.push(element);
						});
					}
				});

			},
			saveAction: function(callback) {
				console.log("保存");
				var count = 1;
				var app_no = localStorage.getItem("APP_NO");
				var cons_no = localStorage.getItem("CONS_NO");
				var user = UserInfo.USER;
				var thisDate = getYYYYMMddDate();
				var IS_FLAG = 0;
				var presentName = this.presentName;
				if(presentName) {
					//更新现名称
					AndroidApi.update('{"tableName": "CUST_ADDRINFO","whereClause":"APP_NO = ? AND CONS_NO = ?","whereArgs":[' + app_no + ',' + cons_no + '],"contentValues":[{"PRESENT_NAME":' + presentName + '}]}', function(msg) {
						console.log("更新现名称:" + JSON.stringify(msg));
						console.log("count:" + count);
						count===2?callback():count++;
					});

				}else{
					count ++;
				}

				this.updateVisit(function(){
					count===2?callback():count++;
				})

				this.$vux.toast.text("保存成功!");

			},
			submitAction: function() {
				console.log("提交");
				const _this = this;
				this.saveAction(function(){
					var cons_no = localStorage.getItem("CONS_NO");
					var app_no = localStorage.getItem("APP_NO");
					//获取安检结果信息
					//COUNT_UN_UP 待上传条数（SC_STAT 02 待下载（移动端初始下载是02，按正常情况下载成功需要改成03已下载	，但是太麻烦了，我们不改，默认02就是已下载））
					AndroidApi.queryTableData('{"jToken":"","whereClause":"select a.*,(SELECT COUNT(b.APP_NO) FROM TS_DTL_Table b WHERE b.APP_NO = a.APP_NO AND b.SC_STAT=?) COUNT_UN_UP from SC_RST_Table a  where a.APP_NO = ? AND a.CONS_NO = ?","whereArgs":["02",' + app_no + ',' + cons_no + ']}', function(msg) {
						console.log("查询安检结果记录:" + JSON.stringify(msg));
						if(msg.resultCode == 9999) {
							let SC_RST = msg.result;
							let scRstSize = SC_RST.length;
							for(let index in SC_RST){
								let SC_RST_NO = SC_RST[index].SC_RST_NO;
								console.log("SC_RST_NO"+SC_RST_NO);
								let COUNT_UN_UP = SC_RST[index].COUNT_UN_UP;
								//获取安检结果信息
								//如果后续查询速度慢，需要加入app_no 和cons_no查询出安检明细表，通过id关联到sc_rst表，再关联SC_RST_NO
								let securityCheckParam = {
									"jToken":"",
									"whereClause":"select * from SC_RST_DTL_Table  where SC_RST_NO = ? and \"1\" = \"1\" ",
									"whereArgs":[ SC_RST_NO ]
								}
								AndroidApi.queryTableData(JSON.stringify(securityCheckParam), function(msg) {
									console.log("查询安检结果明细记录:" + JSON.stringify(msg));
									scRstSize--;
									if(msg.resultCode == 9999) {
										_this.$set(SC_RST[index], "SC_RST_DTL", msg.result);
										//调用上传接口
										console.log("123213213213213");
										console.log("msg.result" + msg.result);
										console.log(SC_RST[index]);
										/**
										 * 批量上传的时候if(COUNT_UN_UP==='1')会有问题，需要改成COUNT_UN_UP ===SC_RST.length
										 */
										//全部查询成功后，再调用上传接口
										if(scRstSize === 0){
											uploadSecurityResult(SC_RST, function(msg) {
												if(msg.resultCode === '9999'){
													if(msg.result.CODE === '0'){
														AndroidApi.update('{"tableName": "TS_DTL_Table","whereClause":"APP_NO = ? AND CONS_NO = ? ","whereArgs":[' + app_no + ',"'+ cons_no+'"],"contentValues":[{"SC_STAT":"04"}]}', function(msg) {
															console.log("更新明细记录:" + JSON.stringify(msg));
														});
														console.log("COUNT_UN_UP" + COUNT_UN_UP);
														if(COUNT_UN_UP==='1'){
															// FEEDBACK(app_no,"02");//结果反馈
															AndroidApi.update('{"tableName": "TSINFO_Table","whereClause":"APP_NO = ?","whereArgs":[' + app_no + '],"contentValues":[{"STATUS":"02"}]}', function(msg) {
																console.log("更新工单记录:" + JSON.stringify(msg));
															});
														}
														_this.$vux.toast.text("提交成功!");
													}else{
														_this.$vux.toast.text(msg.result.DESC);
													}
												}else{
													_this.$vux.toast.text(msg.resultMsg);
												}

											});
										}

									}
								});
							}

						}else{
							_this.$vux.toast.text(msg.resultMsg);
						}
					});
				});

			},
			recordAction: function() {
				alert("长按录音");
			},
			orderShowAction: function(tar) {
				this.orderShow = !this.orderShow;
			},
			//作业状态选择
			select: function(tar, operation, index) {
				operation.isChoose = !operation.isChoose;
				
				if(operation.CODE_VALUE == '01' && operation.isChoose == true){
					this.showEntryInfo = true;
					
				}else{
					this.showEntryInfo = false;
				}
				for(var i = 0; i < this.OperationStates.length; i++) {
					if(i != index) {
						this.OperationStates[i].isChoose = false;
					}
				}
				this.updateVisit(function(){});
			},
			//更新入户情况
			updateVisit(successCall){
				console.log("更新入户情况")
				var _this = this;
				var cons_no = localStorage.getItem("CONS_NO");
				var app_no = localStorage.getItem("APP_NO");
				var thisDate = getYYYYMMddDate();
				var IS_FLAG = 0;
				var isUpdate = false;
				for(var i = 0; i < this.OperationStates.length; i++) {
					if(this.OperationStates[i].isChoose == true) {
						isUpdate = true;
						var VISIT_RST = this.OperationStates[i].CODE_VALUE;
						AndroidApi.queryTableData('{"jToken":"","whereClause":"select * from TURC_INFO_Table where APP_NO = ?  ","whereArgs":[' + app_no + ']}', function(msg) {
							if(msg.resultCode == 9999) {
								let thisDate = dateFormat(new Date(),'YYYY-MM-DD');
								let thisDatetime = dateFormat(new Date(),'YYYY-MM-DD HH:mm:ss');
								let TASK_TYPE = "06";//to-da 需要通过任务类别获取对应的takstype
								let contentValue = {
									SRV_DATE: thisDate,
									ARRIVA_TIME: thisDatetime,
									WORK_EMP_NO: UserInfo.USER,
									WORK_EMP_NAME: UserInfo.REAL_NAME,
									TASK_TYPE: TASK_TYPE,
									VENTILATION_RESULT: "0",
									HOME_SITU: VISIT_RST,
								}
								if(msg.result.length <= 0) {
									contentValue.APP_NO = app_no;
									AndroidApi.insert(JSON.stringify({
										"jToken": "",
										"tableName": "TURC_INFO_Table",
										"contentValues": [contentValue]
									}),function(msg){
										console.log("更新记录:" + JSON.stringify(msg));
										successCall()
									});
								}else{
									AndroidApi.update(JSON.stringify({
											"tableName": "TURC_INFO_Table",
											"whereClause":"APP_NO = ?",
											"whereArgs":[ app_no ],
											"contentValues":[contentValue]
										}), function(msg) {
										console.log("更新记录:" + JSON.stringify(msg));
										successCall()
									});
								}
							} else {
								successCall()
							}
						});

					}
				}
				if(!isUpdate){
					successCall();
				}
			}

		}
	}
</script>

<style scoped lang="less">
	.contentDiv {
		/*padding-bottom: 2rem;*/
		.save {
			color: white;
			position: absolute;
			right: 1.3888rem;
			top: 0.4166rem;
			font-size: 0.4166rem;
		}
		.submit {
			color: white;
			position: absolute;
			right: 0.2777rem;
			top: 0.4166rem;
			font-size: 0.4166rem;
		}
		.userInfo {
			background-color: white;
			.rightArrow {
				display: flex;
				align-items: center;
				justify-content: center;
			}
			.topDiv {
				display: flex;
				img {
					width: 1rem;
					height: 1rem;
					margin-left: 0.4166rem;
					margin-top: 0.3333rem;
				}
				.nameAddress {
					margin-left: 0.4166rem;
					margin-top: 0.2222rem;
					.name {
						font-size: 0.4444rem;
						color: #444444;
					}
					.address {
						font-size: 0.3333rem;
						color: #444444;
						margin-top: 0.1388rem;
					}
					.trouble {
						display: flex;
						margin-top: 0.2083rem;
						.p1 {
							color: white;
							background-color: #159BFD;
							font-size: 0.3333rem;
							height: 0.5rem;
							padding: 0 0.2rem;
							border-radius: 0.25rem;
							display: flex;
							justify-content: center;
							align-items: center;
						}
						.p2 {
							margin-left: 0.8333rem;
							display: flex;
							#title {
								color: #888888;
								font-size: 0.3333rem;
								margin-top: 0.0694rem;
							}
							#number {
								display: flex;
								justify-content: center;
								align-items: center;
								height: 0.5rem;
								font-size: 0.3333rem;
								color: white;
								border-radius: 0.25rem;
								background-color: #FE6261;
								width: 1.1111rem;
								margin-left: 0.0694rem;
							}
						}
					}
				}
			}
			.line {
				border: 0.0138rem solid #D9DAEB;
				margin-top: 0.2777rem;
				margin-left: 0.2777rem;
				margin-right: 0.2777rem;
			}
			.bottomDiv {
				display: flex;
        justify-content: space-between;
        align-items: center;
        // padding: 0.3472rem 0.2777rem;
        height: 1.1111rem;
				input {
					width: 3.4722rem;
					margin-left: 0.2777rem;
          height: 100%;
					font-size: 0.3611rem;
          display: flex;
					align-items: center;
				}
				.lableDiv {
          height: 100%;
					display: flex;
					align-items: center;
					img {
						margin-left: 0.2083rem;
						width: 0.2222rem;
						height: 0.3472rem;
					}
				}
			}
		}
		.workOrderInfo {
			margin-top: 0.2777rem;
			background-color: white;
			.order {
				display: flex;
				justify-content: space-between;
				border-bottom: 0.0138rem solid #D9DAEB;
				div {
					display: flex;
					.rightImg {
						width: 0.2222rem;
						height: 0.3472rem;
						margin-top: 0.375rem;
						margin-right: 0.2777rem;
						margin-left: 0.2777rem;
					}
					.topImg {
						width: 0.3333rem;
						height: 0.2083rem;
						margin-top: 0.375rem;
						margin-right: 0.2777rem;
						margin-left: 0.2777rem;
					}
				}
			}
			.operationDiv {
				display: flex;
				/*align-items: center;*/
				padding-top: 0.3472rem;
				padding-bottom: 0.3472rem;
				margin-left: 0.2777rem;
				font-size: 0.4166rem;
				color: #444444;
				border-bottom: 0.0138rem solid #D9DAEB;
				flex-wrap: wrap;
				a {
					display: flex;
					align-items: center;
					img {
						width: 0.5rem;
						height: 0.5rem;
						margin-left: 0.4166rem;
						margin-right: 0.0694rem;
					}
				}
			}
		}
		.entryInfo {
			margin-top: 0.2777rem;
			background-color: white;
			margin-bottom: 1.3333rem;
		}
		.record {
			position: fixed;
			/*top: 14rem;*/
			left: 0;
			right: 0;
			bottom: 0;
			height: 1.3333rem;
			background-color: white;
			display: flex;
			justify-content: center;
			align-items: center;
			div {
				display: flex;
				justify-content: center;
				align-items: center;
				img {
					width: 0.6111rem;
					height: 0.6111rem;
				}
				p {
					color: #159BFD;
					font-size: 0.4444rem;
				}
			}
		}
	}
</style>